package com.freexiaoyu.cloud.utils

import okhttp3.internal.and
import java.io.UnsupportedEncodingException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 * Created by DIY on 2017/7/31. 16:00
 * author:free宇
 * email:freexiaoyu@foxmail.com
 * describe:
 */
object MD5Util {
    fun md5(s: String): String {
        return try {
            //得到一个信息摘要器
            val digest = MessageDigest.getInstance("md5")
            val result = digest.digest(s.toByteArray())
            val buffer = StringBuffer()
            //要把每一个byte做一个与运算0xff,0xff是十六进制，十进制为255
            for (b in result) {
                //与运算
                val number: Int = b and 0xff
                val str = Integer.toHexString(number)
                //如果位数不够前面加个零
                if (str.length == 1) {
                    buffer.append("0")
                }
                buffer.append(str)
            }
            //标准的md5加密后的结果
            buffer.toString()
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
            ""
        }
    }

    fun md52(s: String): String {
        val hash: ByteArray
        hash = try {
            MessageDigest.getInstance("MD5").digest(s.toByteArray(charset("UTF-8")))
        } catch (e: NoSuchAlgorithmException) {
            throw RuntimeException("Huh, MD5 should be supported?", e)
        } catch (e: UnsupportedEncodingException) {
            throw RuntimeException("Huh, UTF-8 should be supported?", e)
        }
        val hex = StringBuilder(hash.size * 2)
        for (b in hash) {
            if (b and 0xFF < 0x10) hex.append("0")
            hex.append(Integer.toHexString(b and 0xFF))
        }
        return hex.toString()
    }
}